package com.aiton.bamin.bamindaijiadrier.activity;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.widget.SingleBtnDialog;
import com.aiton.bamin.bamindaijiadrier.R;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.aiton.bamin.bamindaijiadrier.model.VersionAndHouTaiIsCanUse;
import com.aiton.bamin.bamindaijiadrier.server.LocationService;
import com.igexin.sdk.PushManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import cz.msebera.android.httpclient.Header;

public class WelcomeActivity extends ZjbBaseActivity {

    private User mUser;
    private boolean isfrist;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("onServiceConnected ", "onServiceConnected aaaaaaaaaa");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    //    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
//    //开启悬浮窗的Service
//    Intent floatWinIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        initPermission();
        PushManager instance = PushManager.getInstance();
        instance.initialize(this.getApplicationContext());
        String clientid = instance.getClientid(WelcomeActivity.this);
        Log.e("onCreate ", "个推CID--------aaaaaaaaaa" + clientid);

        init();
        // TODO: 2016/9/6 关闭服务器检查
        checkVersionAndHouTaiIsCanUse();
//        toMainActivity();

    }

    @Override
    protected void initData() {
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void setListeners() {

    }

    @Override
    protected void initSP() {
        ACache aCache = ACache.get(WelcomeActivity.this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
        SharedPreferences sp = getSharedPreferences(Constant.SP.SP_ISFRIST, 0);
        isfrist = sp.getBoolean("isfrist", true);
    }

    @Override
    protected void initIntent() {

    }

    @Override
    protected void findID() {

    }

    private void initPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    Constant.PERMISSION.ACCESS_COARSE_LOCATION);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    Constant.PERMISSION.ACCESS_FINE_LOCATION);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    Constant.PERMISSION.WRITE_EXTERNAL_STORAGE);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    Constant.PERMISSION.READ_EXTERNAL_STORAGE);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                    Constant.PERMISSION.READ_PHONE_STATE);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_BOOT_COMPLETED)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECEIVE_BOOT_COMPLETED},
                    Constant.PERMISSION.RECEIVE_BOOT_COMPLETED);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请CALL_PHONE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE},
                    Constant.PERMISSION.CALL_PHONE);//自定义的code
        } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.SYSTEM_ALERT_WINDOW)
                != PackageManager.PERMISSION_GRANTED) {
            //申请CALL_PHONE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW},
                    Constant.PERMISSION.SYSTEM_ALERT_WINDOW);//自定义的code
        }

    }

    /**
     * 检查服务器是否存活和当前版本是否可用
     */
    private void checkVersionAndHouTaiIsCanUse() {
        String url = Constant.Url.CHECK_LIVE;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("onResponse ", "检查当前版本是否可用" + s);
                try {
                    VersionAndHouTaiIsCanUse versionAndHouTaiIsCanUse = GsonUtils.parseJSON(s, VersionAndHouTaiIsCanUse.class);
                    if (versionAndHouTaiIsCanUse.getStatus() == 0) {
                        if (versionAndHouTaiIsCanUse.getDatas().isLive()) {
                            toMainActivity();
                        } else {
                            setDialogCkeck(versionAndHouTaiIsCanUse.getDatas().getMessage(), "确认");
                        }
                    } else {
                        setDialogCkeck(versionAndHouTaiIsCanUse.getMes(), "确认");
                    }
                } catch (Exception e) {
                    setDialogCkeck("服务器出错", "确认");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                setDialogCkeck("服务器正在升级，暂停服务", "确认");

            }
        });
    }

    //dialog提示
    private void setDialogCkeck(String messageTxt, String iSeeTxt) {
        final SingleBtnDialog singleBtnDialog = new SingleBtnDialog(this, messageTxt, iSeeTxt);
        singleBtnDialog.setClicklistener(new SingleBtnDialog.ClickListenerInterface() {
            @Override
            public void doWhat() {
                singleBtnDialog.dismiss();
                SysApplication.getInstance().exit();

            }
        });
        singleBtnDialog.show();
    }

    private void toMainActivity() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent();
//                if (isfrist) {
//
//                    intent.setClass(WelcomeActivity.this, GuideActivity.class);
//                } else {
                if (mUser != null) {

                    intent.setClass(WelcomeActivity.this, MainActivity.class);
                } else {
                    intent.setClass(WelcomeActivity.this, LoginActivity.class);
                }
//                }
                startActivityTo(intent);

                finish();
            }
        }, 1000);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent server = new Intent();
        server.setClass(WelcomeActivity.this, LocationService.class);
        bindService(server, conn, Context.BIND_AUTO_CREATE);
        startService(server);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
}
